package org.realogic.cfm.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public final class UtilBlob {
	public static byte[] getBytes(InputStream is) {
		byte[] data = null;

		List<byte[]> chunks = new ArrayList<byte[]>();
		byte[] buffer = new byte[1024 * 512];
		int read = -1;
		int size = 0;

		try {
			while ((read = is.read(buffer)) != -1) {
				if (read > 0) {
					byte[] chunk = new byte[read];
					System.arraycopy(buffer, 0, chunk, 0, read);
					chunks.add(chunk);
					size += chunk.length;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		if (size > 0) {
			ByteArrayOutputStream bos = null;
			try {
				bos = new ByteArrayOutputStream(size);
				for (Iterator<byte[]> itr = chunks.iterator(); itr.hasNext();) {
					byte[] chunk = itr.next();
					bos.write(chunk);
				}
				data = bos.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return data;
	}

	public static void saveBytes(OutputStream os, byte[] bytes) {

		if (bytes != null) {
			ByteArrayInputStream bis = null;

			if (bytes.length > 0) {
				bis = new ByteArrayInputStream(bytes);

				byte[] buffer = new byte[1024 * 512];
				int read = -1;

				try {
					while ((read = bis.read(buffer)) != -1) {
						if (read > 0) {
							byte[] chunk = new byte[read];
							System.arraycopy(buffer, 0, chunk, 0, read);
							os.write(chunk);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (os != null) {
						try {
							os.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}

			}
		}
	}

	public static String get(Reader reader) {
		// 64K
		StringBuffer sb = new StringBuffer(65535);
		try {
			// 每次获取60K
			char[] b = new char[60000];
			int i = 0;
			while ((i = reader.read(b)) != -1) {
				sb.append(b, 0, i);
			}
		} catch (Exception ex) {
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
			}
		}
		return sb.toString();
	}
}
